import Joi from "joi";
import { ResultSetHeader } from "mysql2";
import { getDB } from "~/server/utils/db/mysql/index";
import { getLoginUid, responseJson } from "~/server/utils/helper/index";
/**
 * 1、判断用户是否登录
 * 2、已登录修改文章
 */

export default defineEventHandler(async (event) => {
  // 1、判断用户是否登录
  let uid = getLoginUid(event);
  if (uid === 0) {
    setResponseStatus(event, 401);
    return responseJson(1, "请登录", {});
  }

  // 获取客户端传来的手机号和密码
  const body = await readBody(event);

  // 数据校验
  const schema = Joi.object({
    noteId: Joi.number().required(),
    title: Joi.string().allow(),
    content_md: Joi.string().allow(),
    state: Joi.number().required(),
  });
  try {
    await schema.validateAsync(body);
  } catch (error) {
    return responseJson(1, "参数错误", {});
  }

  const con = getDB();

  try {
    // 确保 noteId 是数字类型
    const noteId = Number(body.noteId);
    if (isNaN(noteId) || noteId <= 0) {
      console.error("无效的 noteId:", body.noteId);
      return responseJson(1, "参数错误：文章ID无效", {});
    }

    const [rows] = await con.execute<ResultSetHeader>(
      "UPDATE `notes` SET `title`=?,`content_md`=?,`state`=? WHERE `id`=? AND `uid`=?",
      [body.title || "", body.content_md || "", body.state, noteId, uid]
    );

    if (rows.affectedRows !== 0) {
      return responseJson(0, "修改成功", {});
    } else {
      console.error("更新文章失败，可能原因：", {
        noteId,
        uid,
        title: body.title,
        state: body.state,
      });
      return responseJson(1, "文章不存在或无权修改", {});
    }
  } catch (error) {
    // 记录错误详情以便调试
    console.error("修改文章失败错误详情:", error);
    if (error instanceof Error) {
      console.error("错误消息:", error.message);
      console.error("错误堆栈:", error.stack);
    }
    return responseJson(1, "修改失败", {});
  }
  // 注意：不要关闭连接池！连接池应该保持打开状态以供后续使用
  // 连接池会自动管理连接的获取和释放
});
